<template>
  <div class="shop-selector">
    <el-form-item label="关联店铺" prop="shopIds">
      <div class="shop-selector-container">
        <!-- 已选择的店铺列表 -->
        <div v-if="selectedShops.length > 0" class="selected-shops">
          <el-tag
            v-for="shop in selectedShops"
            :key="shop.id"
            closable
            type="primary"
            size="default"
            class="shop-tag"
            @close="removeShop(shop.id)"
          >
            {{ shop.shopName }}
            <span v-if="shop.isPrimary" class="primary-indicator">（主要）</span>
          </el-tag>
        </div>
        
        <!-- 添加店铺按钮 -->
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="showShopDialog = true"
          class="add-shop-btn"
        >
          选择店铺
        </el-button>
      </div>
    </el-form-item>

    <!-- 店铺选择对话框 -->
    <el-dialog
      v-model="showShopDialog"
      title="选择店铺"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="shop-dialog-content">
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-form :model="searchForm" :inline="true" class="search-form">
            <el-form-item label="店铺名称">
              <el-input
                v-model="searchForm.shopName"
                placeholder="请输入店铺名称"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="店铺类型">
              <el-select
                v-model="searchForm.shopType"
                placeholder="请选择店铺类型"
                clearable
                style="width: 150px"
              >
                <el-option label="餐饮" :value="1" />
                <el-option label="零售" :value="2" />
                <el-option label="服务" :value="3" />
                <el-option label="其他" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 店铺列表 -->
        <div class="shop-list">
          <el-table
            :data="shopList"
            v-loading="loading"
            stripe
            border
            style="width: 100%"
            max-height="400"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="shopName" label="店铺名称" min-width="150" />
            <el-table-column prop="shopCode" label="店铺编码" width="120" />
            <el-table-column prop="shopTypeName" label="店铺类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getShopTypeTagType(row.shopType)" size="small">
                  {{ row.shopTypeName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="communityName" label="所属社区" min-width="120" />
            <el-table-column prop="buildingName" label="所属楼栋" min-width="120" />
            <el-table-column prop="roomNumber" label="房间号" width="100" />
            <el-table-column prop="area" label="面积(㎡)" width="100">
              <template #default="{ row }">
                <span v-if="row.area && typeof row.area === 'number'" class="area-text">{{ row.area.toFixed(2) }}</span>
                <span v-else-if="row.area && !isNaN(parseFloat(row.area))" class="area-text">{{ parseFloat(row.area).toFixed(2) }}</span>
                <span v-else class="text-placeholder">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="rentPrice" label="租金(元/月)" width="120">
              <template #default="{ row }">
                <span v-if="row.rentPrice && typeof row.rentPrice === 'number'" class="price-text">¥{{ row.rentPrice.toFixed(2) }}</span>
                <span v-else-if="row.rentPrice && !isNaN(parseFloat(row.rentPrice))" class="price-text">¥{{ parseFloat(row.rentPrice).toFixed(2) }}</span>
                <span v-else class="text-placeholder">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="statusName" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ row.statusName }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showShopDialog = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :disabled="tempSelectedShops.length === 0">
            确定选择 ({{ tempSelectedShops.length }})
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { shopApi } from '@/api/shop'
import type { ShopVO, ShopOwnerRelationVO } from '../types'

// Props
interface Props {
  modelValue: ShopOwnerRelationVO[]
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: ShopOwnerRelationVO[]]
}>()

// 响应式数据
const loading = ref(false)
const showShopDialog = ref(false)
const shopList = ref<ShopVO[]>([])
const tempSelectedShops = ref<ShopVO[]>([])

// 搜索表单
const searchForm = reactive({
  shopName: '',
  shopType: null as number | null
})

// 计算属性
const selectedShops = computed(() => props.modelValue || [])

// 生命周期
onMounted(() => {
  loadShopList()
})

// 方法
const loadShopList = async () => {
  loading.value = true
  try {
    // 调用真实API获取店铺列表
    const response = await shopApi.getShopPage({
      current: 1,
      size: 100, // 获取店铺，限制在100以内
      shopName: searchForm.shopName || undefined,
      shopType: searchForm.shopType || undefined,
      status: 1 // 只获取启用的店铺
    })
    
    if (response && response.code === 200 && response.data) {
      shopList.value = response.data.records || []
      console.log('店铺列表加载成功:', shopList.value.length, '个店铺')
    } else {
      ElMessage.error(response?.message || '加载店铺列表失败')
      shopList.value = []
    }
  } catch (error) {
    ElMessage.error('加载店铺列表失败')
    console.error('加载店铺列表失败:', error)
    shopList.value = []
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 重新加载店铺列表，应用搜索条件
  loadShopList()
}

const handleReset = () => {
  searchForm.shopName = ''
  searchForm.shopType = null
  // 重新加载店铺列表
  loadShopList()
}

const handleSelectionChange = (selection: ShopVO[]) => {
  tempSelectedShops.value = selection
}

const handleConfirm = () => {
  if (tempSelectedShops.value.length === 0) {
    ElMessage.warning('请选择至少一个店铺')
    return
  }

  // 转换为关联关系格式
  const newRelations: ShopOwnerRelationVO[] = tempSelectedShops.value.map(shop => ({
    id: 0, // 新增时ID为0
    shopId: shop.id,
    shopName: shop.shopName,
    ownerId: 0, // 将在父组件中设置
    ownerName: '',
    relationType: 1, // 默认为业主
    relationTypeName: '业主',
    isPrimary: 0, // 默认非主要联系人
    status: 1,
    statusName: '启用',
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString()
  }))

  // 合并现有选择
  const existingShopIds = (props.modelValue || []).map(rel => rel.shopId)
  const newRelationsFiltered = newRelations.filter(rel => !existingShopIds.includes(rel.shopId))
  
  const updatedRelations = [...(props.modelValue || []), ...newRelationsFiltered]
  
  emit('update:modelValue', updatedRelations)
  showShopDialog.value = false
  tempSelectedShops.value = []
  
  ElMessage.success(`已选择 ${newRelationsFiltered.length} 个店铺`)
}

const removeShop = (shopId: number) => {
  const updatedRelations = (props.modelValue || []).filter(rel => rel.shopId !== shopId)
  emit('update:modelValue', updatedRelations)
  ElMessage.success('已移除店铺关联')
}

const getShopTypeTagType = (shopType: number) => {
  switch (shopType) {
    case 1: return 'success' // 餐饮
    case 2: return 'primary' // 零售
    case 3: return 'warning' // 服务
    case 4: return 'info'     // 其他
    default: return 'info'
  }
}
</script>

<style scoped>
.shop-selector {
  width: 100%;
}

.shop-selector-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.selected-shops {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 32px;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fafafa;
}

.shop-tag {
  margin: 0;
}

.primary-indicator {
  color: #67c23a;
  font-weight: 600;
  margin-left: 4px;
}

.add-shop-btn {
  align-self: flex-start;
}

.shop-dialog-content {
  max-height: 600px;
}

.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  margin: 0;
}

.shop-list {
  max-height: 400px;
  overflow-y: auto;
}

.dialog-footer {
  text-align: right;
}

.price-text {
  color: #67c23a;
  font-weight: 600;
}

.area-text {
  color: #409eff;
  font-weight: 500;
}

.text-placeholder {
  color: #c0c4cc;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .selected-shops {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
}
</style>
